package tr.edu.yildiz.ce.dap.appagent.process;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.UnknownHostException;

import tr.edu.yildiz.ce.dap.appagent.command.deployment.base.CommandConstants;
import tr.edu.yildiz.ce.dap.appagent.conf.DynamicProxyConfiguration;
import tr.edu.yildiz.ce.dap.appagent.exception.AgentCommunicationException;
import tr.edu.yildiz.ce.dap.appagent.exception.BasicAgentException;
import tr.edu.yildiz.ce.dap.appagent.manager.AgentProcessManager;
import tr.edu.yildiz.ce.dap.appagent.model.DapMessage;
import tr.edu.yildiz.ce.dap.appagent.process.base.AbstractProcess;
import tr.edu.yildiz.ce.dap.appagent.service.infra.NetworkManager;
import tr.edu.yildiz.ce.dap.appagent.util.AgentProperties;

public abstract class MulticastReceiverProcess extends AbstractProcess{

	String multicastAddress;
	Integer port;
	
	public MulticastReceiverProcess(AgentProcessManager processManager, String multicastAddress,Integer port) {
		super(processManager);
		this.port = port;
		this.multicastAddress = multicastAddress;
	}
	
	
	public void run(){
		String s = null;
		NetworkManager networkManager = (NetworkManager) getProcessManager().getService(NetworkManager.class.getName());
	    try{
	        s = networkManager.joinMulticast(multicastAddress, port);
	    }
	    catch (AgentCommunicationException se) {
	    	System.out.println(se.getMessage());
	    	try {
				onMulticastConnectionFailed();
				return ;
			} catch (BasicAgentException e) {
				e.printStackTrace();
			}
	    }
	    try{
	    	onMulticastPacketReceived(s);	
	    }catch (BasicAgentException baException) {
	    	System.out.println(baException.getMessage());
	    }
	    
	}

	protected abstract void onMulticastPacketReceived(String message) throws BasicAgentException ;
	protected abstract void onMulticastConnectionFailed() throws BasicAgentException ;
	
}
